import java.io.UnsupportedEncodingException;

import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreFullException;
import javax.microedition.rms.RecordStoreNotFoundException;


public class RMS {
	
	public static String RMS_name = "store";
	
	
	public static void saveRMS(String filename, byte[]data) throws RecordStoreFullException, RecordStoreNotFoundException, RecordStoreException
	{
		RecordStore rec = RecordStore.openRecordStore(filename, true);
		if (rec.getNumRecords() > 0)
			rec.setRecord(1, data, 0, data.length);
		else {
			rec.addRecord(data, 0, data.length);
		}
		rec.closeRecordStore();
	}

	
	public static void saveInt(String s)
	{
		try {
			saveRMS(RMS_name, s.getBytes("UTF-8"));
		} catch (RecordStoreFullException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RecordStoreNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RecordStoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public static void savegame(int score)
	{
		saveInt(score+"");
	}
	
	
	
	
	public void loadgame()
	{
		
	}
	
	public static int loadScore()
	{
		int score = loadRMSInt(RMS_name);
		return score;
	}
	
	public static int loadRMSInt(String file) {
		String so=loadRMSString(file);
		return so==null?0:Integer.parseInt(so);
	}
	
	public static String loadRMSString(String filename) {
		byte[] data = loadRMS(filename);
		if (data == null)
			return null;
		else
			try {
				String s = new String(data, "UTF-8");
				return s;
			} catch (Exception e) {
				return new String(data);
			}
	}
	
	
	public static byte[] loadRMS(String filename)
	{
		RecordStore rec;
		byte[] data;
		try {
			rec = RecordStore.openRecordStore(filename, false);
			data = rec.getRecord(1);
			rec.closeRecordStore();
		} catch (Exception e) {
			return null;
		}
		// System.out.println("rec " + data);
		return data;
	}
	
}
